package com.hnkywl.sts.service.organ;

import com.google.gson.Gson;
import com.hnkywl.sts.dao.organ.GsjgDao;
import com.hnkywl.sts.dao.organ.NbbmDao;
import com.hnkywl.sts.dao.organ.NbgsDao;
import com.hnkywl.sts.dao.organ.QyjgDao;
import com.hnkywl.sts.entity.organ.Gsjg;
import com.hnkywl.sts.entity.organ.Qyjg;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.util.BaseUtils;
import net.ruixin.orm.hibernate.Page;
import net.ruixin.utils.CollectionUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 说明：
 * 包:        com.hnkywl.sts.service.sys
 * 类描述:    岗位服务类
 * 修改备注: [说明本次修改内容]
 * 版本:        [v1.0]
 */
@Service
public class GsjgService {
    private GsjgDao gsjgDao;
    private NbbmDao nbbmDao;
    private NbgsDao nbgsDao;
    private QyjgDao qyjgDao;

    /**
     * 查询公司机构
     *
     * @param mc       公司机构
     * @param pageNo
     * @param pageSize
     * @return
     */
    public String findAllGsjg(Long id, String mc, Long parentId, String parentMc, int pageNo, int pageSize) {
        Page<Gsjg> gsjgPage = this.gsjgDao.findGsjgList(id, mc, parentId, parentMc, pageNo, pageSize);
        String gsjgJson = BaseUtils.fetchCollectionToJson(gsjgPage.getResult() == null ? new ArrayList<Gsjg>() : gsjgPage.getResult()
                , "id", "qc", "jc", "sjjg.jc", "bz", "sfzx");
        return "{\"total\":" + gsjgPage.getTotalCount() + ",\"rows\":[" + gsjgJson + "]}";
    }

    public String findAllGsjgMc(Long id, String mc, Long parentId, String parentMc, int pageNo, int pageSize) {
        Page<Gsjg> gsjgPage = this.gsjgDao.findGsjgList(id, mc, parentId, parentMc, pageNo, pageSize);
        String gsjgJson = BaseUtils.fetchCollectionToJson(gsjgPage.getResult() == null ? new ArrayList<Gsjg>() : gsjgPage.getResult()
                , "id", "qc", "jc");
        return "[" + gsjgJson + "]";
    }

    /**
     * 查找科目代码列表
     *
     * @param sjjgId
     * @param mc
     * @param kmdm
     * @param pageNo
     * @param pageSize
     * @return
     */
    public String findKmdm(Long sjjgId, String mc, String kmdm, int pageNo, int pageSize) {
        Page<Gsjg> page = gsjgDao.findGsjgList(null, mc, sjjgId, null, pageNo, pageSize);
        List<Gsjg> gsjgList = page.getResult() != null ? page.getResult() : new ArrayList<Gsjg>();
        List<Map> grid = new ArrayList<Map>();
        for (Gsjg gsjg : gsjgList) {
            Map item = new HashMap();
            item.put("gsjg.id", gsjg.getId());
            item.put("gsjg.jc", gsjg.getJc());
            item.put("sjjgJc", gsjg.getSjjg() == null ? null : gsjg.getSjjg().getJc());
            item.put("gsjg.kmdm", gsjg.getKmdm());
            item.put("gsjg.jiuqiUnitCode", gsjg.getJiuqiUnitCode());
            grid.add(item);
        }
        return "{\"total\":" + page.getTotalCount() + ",\"rows\":" + new Gson().toJson(grid) + "}";
    }

    @Transactional
    public Gsjg findGsjgByCode(String code) {
        return gsjgDao.findGsjgByCode(code);
    }

    /**
     * 保存科目代码
     *
     * @param gsjg
     */
    @Transactional
    public void saveKmdm(Gsjg gsjg) {
        Gsjg g = gsjgDao.get(gsjg.getId());
        g.setKmdm(gsjg.getKmdm());
        g.setJiuqiUnitCode(gsjg.getJiuqiUnitCode());
        gsjgDao.save(g);
    }

    /**
     * 公司机构树形展示未启用则不展示
     *
     * @param id 树节点Id
     */
    public String findGsjgTree(Long id) throws Exception {
        String ids;
        if (id == null) {
            ids = CollectionUtils.fetchPropertyToString(gsjgDao.findAllRootGsjg(), "id", ",");
        } else {
            ids = id.toString();
        }
        List<Map> map = gsjgDao.getTree(ids, YgService.getCurrentYg().getCxfw().toString());
        List<Map> tree = new ArrayList<Map>();
        for (Map m : map) {
            Map item = new HashMap();
            if (m.get("PID") != null && ((BigDecimal) (m.get("GSJGLIST"))).intValue() != 0) {
                item.put("state", "closed");
            } else {
                item.put("state", "open");
            }
//            item.put("id", m.get("ID"));
//            item.put("text", m.get("TEXT"));
//            if (m.get("TYPE").equals("nbbm"))
//                item.put("iconCls", "icon-tree-nbbm");
//            else if (m.get("TYPE").equals("nbgs"))
//                item.put("iconCls", "icon-tree-nbgs");
//            item.put("parentId", m.get("PID"));
            if (m.get("TYPE").equals("nbgs")) {
                item.put("parentId", m.get("PID"));
                item.put("iconCls", "icon-tree-nbgs");
                item.put("id", m.get("ID"));
                item.put("text", m.get("TEXT"));
            } else if (m.get("TYPE").equals("nbbm")) {
                item.put("parentId", m.get("PID"));
                item.put("iconCls", "icon-tree-nbbm");
                item.put("id", m.get("ID"));
                item.put("text", m.get("TEXT"));
            }
            tree.add(item);
        }
        return new Gson().toJson(tree);
    }

    /**
     * 公司机构树形展示未启用则不展示
     *
     * @param id 树节点Id
     */
    public String findGsjgTreeJy(Long id, boolean showRoot) throws Exception {
        String ids;
        if (id == null) {
            ids = CollectionUtils.fetchPropertyToString(gsjgDao.findAllRootGsjg(), "id", ",");
        } else {
            ids = id.toString();
        }
        List<Map> map = gsjgDao.getTreeJy(ids);
        if (!showRoot && map.size() > 0) {
            map.remove(0);
        }
        List<Map> tree = new ArrayList<Map>();
        for (Map m : map) {
            Map item = new HashMap();
            item.put("id", m.get("ID"));
            item.put("text", m.get("TEXT"));
            if (m.get("TYPE").equals("nbgs"))
                item.put("iconCls", "icon-tree-nbgs");
            else if (m.get("TYPE").equals("nbbm"))
                item.put("iconCls", "icon-tree-nbbm");
            item.put("parentId", m.get("PID"));
            tree.add(item);
        }
        return new Gson().toJson(tree);
    }

    //无权限公司机构树
    public String findGsjgwqxTreeJy(Long id, boolean showRoot) throws Exception {
        String ids;
        if (id == null) {
            ids = CollectionUtils.fetchPropertyToString(gsjgDao.findAllRootGsjg(), "id", ",");
        } else {
            ids = id.toString();
        }
        List<Map> map = gsjgDao.getTreeJywqx(ids);
        if (!showRoot && map.size() > 0) {
            map.remove(0);
        }
        List<Map> tree = new ArrayList<Map>();
        for (Map m : map) {
            Map item = new HashMap();
            item.put("id", m.get("ID"));
            item.put("text", m.get("TEXT"));
            if (m.get("TYPE").equals("nbgs"))
                item.put("iconCls", "icon-tree-nbgs");
            else if (m.get("TYPE").equals("nbbm"))
                item.put("iconCls", "icon-tree-nbbm");
            item.put("parentId", m.get("PID"));
            tree.add(item);
        }
        return new Gson().toJson(tree);
    }

    //所属机构
    public String findSsGsjgTree(Long id, boolean showRoot) throws Exception {
        String ids;
        if (id == null) {
            ids = CollectionUtils.fetchPropertyToString(gsjgDao.findSsgsjgList(), "id", ",");
        } else {
            ids = id.toString();
        }
        List<Map> map = gsjgDao.getSsTree(ids);
        if (!showRoot && map.size() > 0) {
            map.remove(0);
        }
        List<Map> tree = new ArrayList<Map>();
        for (Map m : map) {
            Map item = new HashMap();
            item.put("id", m.get("ID"));
            item.put("text", m.get("TEXT"));
            if (m.get("TYPE").equals("nbgs"))
                item.put("iconCls", "icon-tree-nbgs");
            else if (m.get("TYPE").equals("nbbm"))
                item.put("iconCls", "icon-tree-nbbm");
            item.put("parentId", m.get("PID"));
            tree.add(item);
        }
        return new Gson().toJson(tree);
    }

    //获取公司本部
    public String getGsbb() throws Exception {
        String ids = CollectionUtils.fetchPropertyToString(gsjgDao.findAllRootGsjg(), "id", ",");
        List<Map> list = gsjgDao.getGsbb(ids);
        List<Map> tree = new ArrayList<Map>();
        for (Map m : list) {
            Map item = new HashMap();
            item.put("id", m.get("ID"));
            item.put("text", m.get("TEXT"));
            if (m.get("TYPE").equals("nbgs"))
                item.put("iconCls", "icon-tree-nbgs");
            else if (m.get("TYPE").equals("nbbm"))
                item.put("iconCls", "icon-tree-nbbm");
            item.put("parentId", m.get("PID"));
            tree.add(item);
        }
        return new Gson().toJson(tree);
    }

    /**
     * 获得公司机构树包括没有启用的
     *
     * @return
     */
    public String findAllGsjgTree(Long gsjgId) throws Exception {
        String ids;
        if (gsjgId == null) {
            ids = CollectionUtils.fetchPropertyToString(gsjgDao.findAllRootGsjg(), "id", ",");
        } else {
            ids = gsjgId.toString();
        }
        List<Map> map = gsjgDao.getTreeZx(ids, YgService.getCurrentYgCxfw());
        List<Map> tree = new ArrayList<Map>();
        for (Map m : map) {
            Map item = new HashMap();
            if (m.get("PID") != null && ((BigDecimal) (m.get("GSJGLIST"))).intValue() != 0) {
                item.put("state", "closed");
            } else {
                item.put("state", "open");
            }


            item.put("id", m.get("ID"));
            item.put("text", m.get("TEXT"));
            if (m.get("TYPE").equals("nbgs"))
                item.put("iconCls", "icon-tree-nbgs " + (!m.get("SFZX").toString().equals("0") ? "gsjg-tree-disabled" : ""));
            else if (m.get("TYPE").equals("nbbm"))
                item.put("iconCls", "icon-tree-nbbm " + (!m.get("SFZX").toString().equals("0") ? "gsjg-tree-disabled" : ""));
            item.put("parentId", m.get("PID"));
            tree.add(item);
        }
        return new Gson().toJson(tree);
    }

    //获得子机构的名称列表，用于级联
    public String findChildren(Long id, Integer type) {
        List<Gsjg> gsjgList = new ArrayList<Gsjg>();

        String dataRegion = "";
        if (YgService.getCurrentYgCxfw() == 2 || YgService.getCurrentYgCxfw() == 3) {
            dataRegion += " id=" + YgService.getCurrentYgGsId() + " and ";
        }

        if (type != null && type == 0) {
            if (id == 1) {
                gsjgList = gsjgDao.find("from Gsjg where " + dataRegion + " sjjg.id = ? and type = ? and jc!='财务部' and sfzx = false order by pxh asc,dateCreated desc", id, "nbbm");
                gsjgList.addAll(gsjgDao.find("from Gsjg where " + dataRegion + " sjjg.id=18"));
            } else
                gsjgList = gsjgDao.find("from Gsjg where " + dataRegion + " sjjg.id = ? and type = ? and sfzx = false order by pxh asc,dateCreated desc", id, "nbbm");
        } else if (type != null && type == 1) {
            if (id == 1) {
                gsjgList = gsjgDao.find("from Gsjg where " + dataRegion + " sjjg.id = ? and type = ? and sfzx = false order by pxh asc,dateCreated desc", id, "nbgs");
                gsjgList.addAll(gsjgDao.find("from Gsjg where " + dataRegion + " sjjg.id=18"));
            } else
                gsjgList = gsjgDao.find("from Gsjg where " + dataRegion + " sjjg.id = ? and type = ? and jc!='财务部' and sfzx = false order by pxh asc,dateCreated desc", id, "nbgs");
        } else {
            if (YgService.getCurrentYgCxfw() == 2 || YgService.getCurrentYgCxfw() == 3) {
                gsjgList = gsjgDao.findByCriteria(new Criterion[]{Restrictions.eq("id", YgService.getCurrentYgGsId()), Restrictions.eq("sjjg.id", id)});
            } else {
                gsjgList = gsjgDao.findByCriteria(new Criterion[]{Restrictions.eq("sjjg.id", id)});
            }
        }
        return "[" + BaseUtils.fetchCollectionToJson(gsjgList, "id", "jc") + "]";
    }

    public String findJyChildren(Long id, Integer type) {
        List<Gsjg> gsjgList = new ArrayList<Gsjg>();
        if (type != null && type == 0)
            gsjgList = gsjgDao.find("from Gsjg where sjjg.id = ? and type = ? and sfzx = false and sfjyzz = true order by pxh asc,dateCreated desc", id, "nbbm");
        return "[" + BaseUtils.fetchCollectionToJson(gsjgList, "id", "jc") + "]";
    }

    /**
     * 查询公司机构明细
     *
     * @param id 公司机构名称
     * @return
     */
    @Transactional
    public Gsjg findGsjgDetail(Long id) {
        return this.gsjgDao.get(id);
    }

    @Transactional
    public List findGsjgYgDetailByName(String name) {
        return this.gsjgDao.findGsjgYgDetailByName(name);
    }

    @Transactional
    public List findGsjgYgDetailById(Long id) {
        return this.gsjgDao.findGsjgYgDetailById(id);
    }

    @Transactional
    public void startGsjg(Long id) {
        Gsjg gsjg = gsjgDao.get(id);
        if (gsjg.getSjjg() != null && gsjg.getSjjg().getSfzx())
            throw new RuntimeException("启用失败！父机构未启用");
        gsjg.setLastUpdated(new Date());
        gsjg.setSfzx(false);
        this.gsjgDao.save(gsjg);
    }

    public String getZgjsJc() {
        Object gsjgId = this.gsjgDao.findSjjgName(YgService.getCurrentYg().getId());
        if (gsjgId != null) {
            Gsjg gsjg = gsjgDao.get(Long.parseLong(gsjgId.toString()));
            return gsjg.getJc() + "-";
        } else {
            return "";
        }

    }

    @Transactional
    public void stopGsjg(Long id) {
        Gsjg gsjg = gsjgDao.get(id);
        if (gsjgDao.find("from Gsjg where sjjg.id = ? and sfzx = true", id).size() != 0) {
            throw new RuntimeException("禁止停用！存在子机构");
        }
        if (gsjg.getYgList() != null && gsjg.getYgList().size() != 0) {
            throw new RuntimeException("禁止停用！存在员工");
        }
        gsjg.setLastUpdated(new Date());
        gsjg.setSfzx(true);
        this.gsjgDao.save(gsjg);
    }

    @Transactional
    public void deleteGsjg(Long id) {
        Gsjg gsjg = gsjgDao.get(id);
        if (gsjg.getSfzx() != null && !gsjg.getSfzx()) {
            throw new RuntimeException("禁止删除！机构已启用");
        }
        if (gsjg.getGsjgList() != null && gsjg.getGsjgList().size() != 0) {
            throw new RuntimeException("禁止删除！存在子机构");
        }
        if (gsjg.getYgList() != null && gsjg.getYgList().size() != 0) {
            throw new RuntimeException("禁止删除！存在员工");
        }
        gsjg.setLastUpdated(new Date());
        gsjg.setDeleted(1);
        this.gsjgDao.save(gsjg);
    }

    /**
     * 获取下一个同层次的排序号
     *
     * @param gsjgId 公司机构的Id
     * @return
     */
    public Integer findNextPxh(Long gsjgId) {
        return gsjgDao.findMaxPxh(gsjgId) == null ? 0 : gsjgDao.findMaxPxh(gsjgId) + 1;
    }

    /**
     * 获取公司机构的编码
     *
     * @return
     */
    public String findBm() {
        return "";
    }

    /**
     * ajax远程验证
     *
     * @param value 验证值
     * @param field 验证字段
     * @param type
     * @return
     */
    public boolean ajaxValidateGsjg(Long id, String value, String field, Integer type) {
        if (type == 0) {
            return nbbmDao.checkUnique(id, value, field);
        } else {
            return nbgsDao.checkUnique(id, value, field);
        }
    }

    /**
     * ajax远程验证
     *
     * @param value 验证值
     * @param field 验证字段
     * @return
     */
    public boolean ajaxValidate(Long id, String value, String field, Long sjjgId) {
        return gsjgDao.checkUnique(id, value, field, sjjgId);
    }

    /**
     * 根据名称查询公司机构
     *
     * @param providerCode
     * @param providerCode
     */
    public Qyjg findGsjgByProvideCode(String providerCode, String providerName) {
        String sql = "select tg.id from t_sys_gsjg tg, t_sys_bggys tb " +
                " where tg.deleted = 0  and tb.qyjg_id = tg.id and (tb.bggysbm = ? or tg.qc = ? ) ";
        List list = this.gsjgDao.findBySQL(sql, providerCode, providerName);
        if (!list.isEmpty()) {
            BigDecimal id = (BigDecimal) list.get(0);
            Qyjg qyjg = this.qyjgDao.get(id.longValue());
            return qyjg;
        }
        if (list.isEmpty()) {
            sql = "select id from t_sys_gsjg where qc=? and deleted=0 ";
            list = this.gsjgDao.findBySQL(sql, providerName);
            if (list.isEmpty())
                return null;
            BigDecimal id = (BigDecimal) list.get(0);
            Qyjg qyjg = this.qyjgDao.get(id.longValue());
            sql = " insert into t_sys_bggys(id,qyjg_id,bggysbm) values(seq_sys_bggys.nextval,?,?) ";
            this.qyjgDao.executeSQL(sql, id, providerCode);
            return qyjg;
        }
        return null;
    }

    /**
     * 查询所有的企业机构和内部公司
     *
     * @param jc
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Transactional
    public String findGsjgAndQyjg(String jc, int pageNo, int pageSize) {
        List<Map> allPage = this.gsjgDao.findGsjgAndQsjgJcList(jc, pageNo, pageSize);
        Gson gson = new Gson();
        String result = gson.toJson(allPage);
        return result;
    }

    @Transactional
    public String findGsjgAndQyjgByQc(String qc, int pageNo, int pageSize) {
        List<Map> allPage = this.gsjgDao.findGsjgAndQsjgQcList(qc, pageNo, pageSize);
        Gson gson = new Gson();
        String result = gson.toJson(allPage);
        return result;
    }

    @Transactional
    public String findXyKhByHtId_qclist(Long htId, String qc, int pageNo, int pageSize) {
        List<Map> allPage = this.gsjgDao.findXyKhByHtId_qclist(htId, qc, pageNo, pageSize);
        Gson gson = new Gson();
        String result = gson.toJson(allPage);
        return result;
    }

    @Transactional
    public String findNbgsByHtId_qclist(Long htId, String qc, int pageNo, int pageSize) {
        List<Map> allPage = this.gsjgDao.findNbgsByHtId_qclist(htId, qc, pageNo, pageSize);
        Gson gson = new Gson();
        String result = gson.toJson(allPage);
        return result;
    }

    //公司部门级联树没有权限限制
    public String findChildrenBmNotWithQx(Long id, Integer type) {
        List<Gsjg> gsjgList = new ArrayList<Gsjg>();

        if (type != null && type == 0)
            gsjgList = gsjgDao.find("from Gsjg where  sjjg.id = ? and type = ? and sfzx = false order by pxh asc,dateCreated desc", id, "nbbm");
        else if (type != null && type == 1)
            gsjgList = gsjgDao.find("from Gsjg where  sjjg.id = ? and type = ? and sfzx = false order by pxh asc,dateCreated desc", id, "nbgs");
        else {
            gsjgList = gsjgDao.findByCriteria(new Criterion[]{Restrictions.eq("id", YgService.getCurrentYgGsId()), Restrictions.eq("sjjg.id", id)});

        }
        return "[" + BaseUtils.fetchCollectionToJson(gsjgList, "id", "jc") + "]";
    }

    public Gsjg findKhByEsbcode(String EsbCode) {
        return this.gsjgDao.findKhByEsbcode(EsbCode);
    }

    @Autowired
    public void setGsjgDao(GsjgDao gsjgDao) {
        this.gsjgDao = gsjgDao;
    }

    @Autowired
    public void setNbbmDao(NbbmDao nbbmDao) {
        this.nbbmDao = nbbmDao;
    }

    @Autowired
    public void setNbgsDao(NbgsDao nbgsDao) {
        this.nbgsDao = nbgsDao;
    }

    @Autowired
    public void setQyjgDao(QyjgDao qyjgDao) {
        this.qyjgDao = qyjgDao;
    }
}
